package com.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.manage.common.result.Result;
import com.manage.common.utils.JwtUtil;
import com.manage.dao.CmSysUserMapper;
import com.manage.pojo.dto.LoginDTO;
import com.manage.pojo.entity.CmSysUser;
import com.manage.pojo.entity.LoginBody;
import com.manage.pojo.entity.RegisterBody;
import com.manage.service.AuthService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private CmSysUserMapper cmSysUserMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 直接注入 UserDetailsService 而不是 AuthenticationManager
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public Result login(LoginBody loginBody) {
        // 1. 查询用户
        CmSysUser user = cmSysUserMapper.selectOne(
                Wrappers.<CmSysUser>lambdaQuery()
                        .eq(CmSysUser::getUsername, loginBody.getUsername())
                        .isNull(CmSysUser::getDeleteTime)
        );


        if (user == null) {
            return new Result().fail("用户不存在");
        }

        // 2. 验证密码
        if (!passwordEncoder.matches(loginBody.getPassword(), user.getPassword())) {
            return new Result().fail("密码错误");
        }
        // 3. 生成 JWT Token（不需要显式调用 AuthenticationManager）
        LoginDTO loginDTO = BeanUtil.toBean(user,LoginDTO.class);
        return new Result(Result.SUCCESS,"登录成功",loginDTO);
    }

    @Override
    public String register(RegisterBody registerBody) {
        // 1. 查询用户
        CmSysUser user = cmSysUserMapper.selectOne(
                Wrappers.<CmSysUser>lambdaQuery()
                        .eq(CmSysUser::getUsername, registerBody.getUsername())
                        .isNull(CmSysUser::getDeleteTime)
        );
        if (user != null) {
            throw new RuntimeException("用户已存在");
        }
        CmSysUser cmSysUser = new CmSysUser();
        cmSysUser.setUsername(registerBody.getUsername());
        cmSysUser.setPassword(passwordEncoder.encode(registerBody.getPassword()));
        cmSysUser.setName(registerBody.getName());
        // 生成盐值（UUID随机字符串）
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        cmSysUser.setSalt(salt);
        cmSysUserMapper.insert(cmSysUser);
        return "注册成功";
    }
}
